package com.base.common.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Looper;
import android.widget.Toast;

import com.yf.cmw.R;

public class ToastAlert {

    private static Context context;
    private static Toast toast;

    public static void init(Context context) {
        ToastAlert.context = context;
    }

    public static void showMsg(String msg) {
        try{
            if (toast == null) {
                toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
            } else {
                toast.setText(msg);
            }
            toast.show();
        }catch (Exception ex){
            //解决在子线程中调用Toast的异常情况处理
            Looper.prepare();
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            Looper.loop();
        }

    }

    public static void showMsg(int resid) {
        if (toast == null) {
            toast = Toast.makeText(context, resid, Toast.LENGTH_LONG);
        } else {
            toast.setText(resid);
        }
        toast.show();
    }

    public static void cancel() {
        if (toast != null) {
            toast.cancel();
        }
    }


    public static void confirm(Context _context,String title, String content, final DialogCallback callback){
        AlertDialog alertDialog = new AlertDialog.Builder(_context)
                .setTitle(title)
                .setMessage(content)
                .setIcon(R.mipmap.ic_launcher)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //Toast.makeText(context, "这是确定按钮", Toast.LENGTH_SHORT).show();
                        if(null != callback) callback.execute(ACTIONBTN_OK);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if(null != callback) callback.execute(ACTIONBTN_CANCEL);
                    }
                }).create();
        alertDialog.show();
    }

    /**
     *  确认框 --> 确认按钮
     */
    public static final String ACTIONBTN_OK = "ACTIONBTN_OK";
    /**
     *  确认框 --> 取消按钮
     */
    public static final String ACTIONBTN_CANCEL = "ACTIONBTN_CANCEL";

    public interface DialogCallback{
        void execute(String actionBtn);
    }
}
